#!/bin/bash

[[ -n $DEBUG ]] && set -x
set -euo pipefail
IFS=$'\n\t'
prog=$(basename "$0")

date_fotmat='%Y-%m-%d %H:%M:%S'

_log() {
  echo "[$(date +"${date_fotmat}")]: $*"
}

_warn() {
  echo -e "\033[1;33m[$(date +"${date_fotmat}")]: $*\033[0m" >&2
}

_err() {
  echo -e "\033[1;31m[$(date +"${date_fotmat}")]: $*\033[0m" >&2
  exit 1
}

# a list show all items needs to install by apt
target_items=(
  # base software
  "net-tools"
  "util-linux" # column etc
  "wget"
  "curl"
  "tmux"
  "python3-pip"
  "python-is-python3"
  "jq"
  "htop"

  # develop
  "git"
  "make"            # make
  "build-essential" # build toolkit, include gcc etc.
  "lua5.1"          # blink_cmp_fuzzy in nvim
  "openssh-server"

  # enchance
  "cmake"
  "pipx"
)

usage() {
  echo "============================="
  echo "Descption: $prog prepare my ubuntu enviroment by install base software and set custom config."
  echo "Usage: $prog"
  echo "       $prog                                note: show help message"
  echo "       $prog help                           note: show help message"
  echo "       $prog check                          note: check all software need to install"
  echo "       $prog prepare                        note: start prepare enviroment"
  echo "============================="
}

apt_install() {
  _log "execute: apt install $@ -y"
  sudo apt install "$@" -y
}

prepare() {
  _log "start prepare environment..."
  local flag=0
  for target_item in "${target_items[@]}"; do
    apt_install "${target_item}"
    flag=1
  done

  if [[ "${flag}" -eq 0 ]]; then
    _warn "there is no any software needs to install."
  else
    _log "prepare enviroment finish, check status..."
    check
  fi
}

check() {
  echo "================================================"
  echo "check all target items if installed..."
  echo "================================================"
  for item in "${target_items[@]}"; do
    local query_result=$(dpkg -l | grep "^ii  ${item} ")
    if [ -z "${query_result}" ]; then
      echo -e "\033[1;31m[×] ${item}\033[0m" >&2
    else
      echo "[√] ${query_result#ii  }"
    fi
  done
}

main() {
  if [[ $# -lt 1 || "$1" == "-h" || "$1" == "--help" ]]; then
    # show help
    usage
    exit 0
  fi
  case "$1" in
  "help" | "h") usage ;;
  "check") check ;;
  "prepare") prepare ;;
  *) usage ;;
  esac

}

main "$@"
